package com.tanhua.server.service;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.common.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class UserService {
    /**
     * 通过sso的rest接口查询验证token
     *
     * @param token
     * @return
     */
//注入工具类bean  连接远程服务
    @Autowired
    private RestTemplate restTemplate;
    @Value("${tanhua.sso.url}")
    private String url;
    //定义一个json转换工具对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    public User queryUserByToken(String token) {
        String ssoUrl = url + "/user/" + token;
        try {
            String data = this.restTemplate.getForObject(ssoUrl, String.class);
            if(StringUtils.isEmpty(data)){
                return  null;
            }
            //把json数据装换成user对象
            return MAPPER.readValue(data, User.class);
        } catch (Exception e) {
            log.error("校验token出错...token=" + token, e);
        }
        return null;
    }
}
